<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import {
  BookOutlined,
  PlusOutlined,
  MoreOutlined,
} from '@ant-design/icons-vue';
import {
  List,
  Card,
  Tag,
  Typography,
  Dropdown,
  Menu,
  MenuItem,
  Popconfirm,
  Pagination,
  Spin,
  theme,
  Layout,
} from 'ant-design-vue';

import {
  repositoryList,
  repositoryRemove,
} from '#/api/knowledge/repository';
import type {
  RepositoryVO,
  RepositoryForm,
} from '#/api/knowledge/repository/model';

import repositoryDrawer from './repository-drawer.vue';
import { querySchema } from './data';
import { useVbenForm } from '#/adapter/form';



import { useRouter } from 'vue-router';

// =============================================================================
// State and Data Management
// =============================================================================

const router = useRouter();
const list = ref<RepositoryVO[]>([]);
const loading = ref(true);
const searchParams = ref<Partial<RepositoryForm>>({});

const pagination = reactive({
  current: 1,
  pageSize: 9,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['4', '9', '14', '19'],
});

const displayList = computed(() => {
  const createCard = { id: 'create-new', isCreate: true };
  // @ts-ignore
  return [createCard, ...list.value];
});


const [QueryForm, formApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: handleSearch,
  schema: querySchema(),
  submitButtonOptions: {
    content: '查询',
  },
  // 大屏一行显示3个，中屏一行显示2个，小屏一行显示1个
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});

async function fetchData() {
  loading.value = true;
  try {
    const params = await formApi.getValues();
    searchParams.value = params;
    const { rows, total } = await repositoryList({
      baseType: 'EDUCATION',
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...params,
    });
    list.value = rows;
    pagination.total = total;
  } catch (error) {
    console.error('Failed to fetch repository list:', error);
  } finally {
    loading.value = false;
  }
}

async function handleSearch() {
  pagination.current = 1;
  await fetchData();
}

function handlePaginationChange(page: number, pageSize: number) {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchData();
}

onMounted(fetchData);

const [RepositoryDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: repositoryDrawer,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

function handleEdit(row: RepositoryVO) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

function handleCardDbClick(item: RepositoryVO) {
  router.push(`/knowledge/education-list/${item.id}/${item.name}`);
}

async function handleDelete(id: string) {
  await repositoryRemove(id);
  fetchData();
}

const { token } = theme.useToken();
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full flex-col">
      <!-- 搜索 Layout -->
      <Layout class="bg-background mb-4 flex-none rounded-lg p-4">
        <QueryForm />
      </Layout>

      <!-- 内容 Layout -->
      <Layout class="bg-background flex min-h-0 flex-1 flex-col rounded-lg p-4">
        <!-- Scrollable Area -->
        <div class="flex-1 overflow-y-auto px-2 pt-3">
          <Spin :spinning="loading">
            <!-- @ts-ignore -->
            <List
              :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 3, xl: 4, xxl: 5 }"
              :data-source="displayList"
              :pagination="false"
            >
              <template #renderItem="{ item }">
                <List.Item>
                  <!-- 创建卡片 -->
                  <div
                    v-if="item.isCreate"
                    class="create-card-aurora"
                    @click="handleAdd"
                  >
                    <div class="aurora-bg"></div>
                    <div class="content-glass">
                      <PlusOutlined class="icon" />
                      <p class="text">创建问答库</p>
                    </div>
                  </div>

                  <!-- 数据卡片 -->
                  <Card
                    v-else
                    :body-style="{ padding: 0, height: '100%' }"
                    :bordered="false"
                    class="folder-card"
                    hoverable
                    style="height: 180px"
                    @dblclick="handleCardDbClick(item)"
                  >
                    <div class="flex h-full flex-col">
                      <div
                        class="folder-tab-icon"
                        :style="{
                          backgroundColor: token.colorBgElevated,
                          borderColor: token.colorBorderSecondary,
                        }"
                      >
                        <BookOutlined
                          :style="{
                            color: token.colorPrimary,
                            fontSize: '18px',
                          }"
                        />
                      </div>

                      <div class="absolute right-3 top-3 z-10">
                        <Dropdown placement="bottomRight">
                          <MoreOutlined
                            class="cursor-pointer text-lg"
                            :style="{ color: token.colorTextTertiary }"
                          />
                          <template #overlay>
                            <Menu>
                              <MenuItem @click="handleEdit(item)"
                                >编辑</MenuItem
                              >
                              <Popconfirm
                                title="确认删除此常见问题库吗？"
                                ok-text="确认"
                                cancel-text="取消"
                                @confirm="handleDelete(item.id)"
                              >
                                <MenuItem>删除</MenuItem>
                              </Popconfirm>
                            </Menu>
                          </template>
                        </Dropdown>
                      </div>

                      <div
                        class="flex flex-grow flex-col justify-between px-4 pb-4 pt-4"
                      >
                        <div>
                          <Typography.Title
                            :level="4"
                            class="!mb-2"
                            :ellipsis="{ tooltip: item.name }"
                            :content="item.name"
                          />
                          <Typography.Paragraph
                            :ellipsis="{ rows: 2, tooltip: item.description }"
                            class="h-[42px] text-sm"
                            :style="{ color: token.colorTextSecondary }"
                            :content="item.description || '暂无描述'"
                          />
                        </div>

                        <div
                          class="mt-2 flex items-center justify-between border-t pt-2"
                          :style="{
                            borderTop: `1px solid ${token.colorSplit}`,
                          }"
                        >
                          <span
                            class="text-xs"
                            :style="{ color: token.colorTextTertiary }"
                          >
                            创建者: {{ item.createByName || '-' }}
                          </span>
                          <Tag color="green">常见问题库</Tag>
                        </div>
                      </div>
                    </div>
                  </Card>
                </List.Item>
              </template>
            </List>
          </Spin>
        </div>

        <!-- Pagination -->
        <div
          v-if="pagination.total > 0"
          class="mt-4 flex flex-none justify-end border-t pt-4"
          :style="{ borderColor: token.colorBorderSecondary }"
        >
          <Pagination v-bind="pagination" @change="handlePaginationChange" />
        </div>
      </Layout>
    </div>

    <!-- 抽屉 -->
    <RepositoryDrawer @reload="fetchData" />
  </Page>
</template>

<style scoped>
.folder-card {
  position: relative;
  border-radius: 8px;
  border: 1px solid v-bind('token.colorBorderSecondary');
  background-color: v-bind('token.colorBgContainer');
  box-shadow: v-bind('token.boxShadowSecondary');
  transition: all 0.3s ease;
  margin-bottom: 40px;
}

.folder-card:hover {
  transform: translateY(-4px);
  box-shadow: v-bind('token.boxShadow');
}

.folder-tab-icon {
  position: absolute;
  top: -16px;
  left: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
}

.create-card-aurora {
  height: 180px;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.create-card-aurora:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 20px -5px rgba(0, 0, 0, 0.15);
}

.create-card-aurora:hover .icon {
  transform: scale(1.2);
}

.aurora-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: v-bind('token.colorBgLayout');
}

.aurora-bg::before,
.aurora-bg::after {
  content: '';
  position: absolute;
  border-radius: 50%;
  filter: blur(60px);
  transition: all 0.8s ease;
}

.aurora-bg::before {
  width: 120px;
  height: 120px;
  background-color: v-bind("token.colorPrimary + '4D'");
  /* 30% opacity */
  top: -20%;
  left: -10%;
}

.aurora-bg::after {
  width: 150px;
  height: 150px;
  background-color: v-bind("token.colorPrimary + '26'");
  /* 15% opacity */
  bottom: -25%;
  right: -15%;
}

.create-card-aurora:hover .aurora-bg::before {
  transform: scale(1.5) translateX(20px);
}

.create-card-aurora:hover .aurora-bg::after {
  transform: scale(1.3) translateY(-20px);
}

.content-glass {
  position: absolute;
  top: 4px;
  left: 4px;
  right: 4px;
  bottom: 4px;
  border-radius: 6px;
  background: v-bind("token.colorBgContainer + '80'");
  /* 50% opacity */
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid v-bind("token.colorBorder + '4D'");
  /* 30% opacity */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.icon {
  font-size: 40px;
  color: v-bind('token.colorPrimary');
  transition: transform 0.3s ease;
}

.text {
  margin-top: 8px;
  font-size: 16px;
  font-weight: bold;
  color: v-bind('token.colorText');
}
</style>
